from modules import predict_modules_V2 as predict_V2  
import os
import glob
from config import config
from dataset import dataset_from_csv as csv_dataset
import time
from datetime import timedelta


feature_names_list=config.feature_names
label_names_list=config.label_names
# input文件夹
foler_path=os.path.join(config.project_dir, config.input_dir_name)

model_dir=os.path.join(config.project_dir, config.model_dir_name)
save_dir=os.path.join(config.project_dir, config.predict_dir_name)
scaler_path=os.path.join(config.project_dir, config.scaler_dir_name)
model_counts = len(glob.glob(os.path.join(model_dir, '*.h5')))

# 找到所有一级日期子文件夹并排序
date_dirs = sorted([p for p in glob.glob(os.path.join(foler_path, '*')) if os.path.isdir(p)])
# ⏱️ 全部日期总时间计时器
all_start_time = time.time()

for date_dir in date_dirs:
    
    date_start_time = time.time()   
    csv_paths = sorted(glob.glob(os.path.join(date_dir, '*.csv')))
    last_tail = [None] * model_counts # ★ 每个日期文件夹启动时重置
    for file_path in csv_paths:
        # 读取数据集,只读取一次
        csvdataset=csv_dataset.LSTMDatasetfromCSV(file_path=file_path, ncodecsv=False).get_data_from_csv()
        predictor = predict_V2.MultiModelPredictor_V2(
            dataset_original=csvdataset,
            file_path=file_path,
            model_input_headers=feature_names_list,
            model_dir=model_dir,
            prediction_column_names=label_names_list,
            save_dir=save_dir,
            train_size=0,
            timestep=50,
            scaler_path=scaler_path
        )
        predictions = predictor.Predict_all(last_tail)
        last_tail   = predictor.last_tails          # 只在当前日期内传递
        predictor.save_prediction_to_csv(predictions)
    date_end_time = time.time()
    date_elapsed = timedelta(seconds=date_end_time - date_start_time)
    print(f"✅ 日期 {os.path.basename(date_dir)} 完成预测，用时: {str(date_elapsed).split('.')[0]}")
# ⏱️ 打印总时间
all_end_time = time.time()
all_elapsed = timedelta(seconds=all_end_time - all_start_time)
print(f"\n🎉 所有日期预测完成，总耗时: {str(all_elapsed).split('.')[0]}")